 
# Import necessary libraries
from nltk.parse import stanford
from nltk.tree import ParentedTree

# Set the path to the Stanford Parser
stanford_parser_path = 'stanford-parser-full-2018-10-17/stanford-parser.jar'
stanford_models_path = 'stanford-parser-full-2018-10-17/stanford-parser-3.9.2-models.jar'

# Set the path to the input file
input_file_path = 'input.txt'

# Set the path to the output file
output_file_path = 'output.txt'

# Set the target entities
entity1 = 'apple'
entity2 = 'orange'

# Load the Stanford Parser
parser = stanford.StanfordParser(path_to_jar=stanford_parser_path, path_to_models_jar=stanford_models_path)

# Parse the input file
with open(input_file_path, 'r') as f:
    sentences = f.readlines()

sentences = ["A trillion gallons of water have been poured into an empty region of outer space.", ]
# Find the shortest dependency path between the target entities
with open(output_file_path, 'w') as f:
    for sentence in sentences:
        tree = ParentedTree.fromstring(str(list(parser.raw_parse(sentence))[0]))
        entity1_node = None
        entity2_node = None
        for subtree in tree.subtrees():
            if subtree.label() == 'NP' and entity1 in subtree.leaves():
                entity1_node = subtree
            elif subtree.label() == 'NP' and entity2 in subtree.leaves():
                entity2_node = subtree
            if entity1_node is not None and entity2_node is not None:
                break
        if entity1_node is None or entity2_node is None:
            f.write('No path found between {} and {}\n'.format(entity1, entity2))
        else:
            path = []
            node = entity1_node
            while node != tree:
                path.append(node)
                node = node.parent()
            node = entity2_node
            while node != tree:
                if node in path:
                    path = path[:path.index(node)+1]
                    break
                path.append(node)
                node = node.parent()
            f.write('Shortest dependency path between {} and {}: {}\n'.format(entity1, entity2, ' -> '.join([str(node[0]) for node in path])))




